package com.foogui.bootjdbctemplate.dao;

import com.foogui.bootjdbctemplate.callback.CallbackJdbcTemplate;
import com.foogui.bootjdbctemplate.callback.StatementCallback;
import com.foogui.bootjdbctemplate.template.OrderJdbcTemplate;
import conm.foogui.common.po.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class OrderRepositoryImpl implements OrderRepository {

    private JdbcTemplate jdbcTemplate;
    @Autowired
    private CallbackJdbcTemplate callbackJdbcTemplate;

    private OrderJdbcTemplate orderJdbcTemplate;

    // 构造器方式注入bean
    @Autowired
    public OrderRepositoryImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // set方式注入
    @Autowired
    public void setOrderJdbcTemplate(OrderJdbcTemplate orderJdbcTemplate) {
        this.orderJdbcTemplate = orderJdbcTemplate;
    }

    /**
     * 方式一：jdbctemplate提供的查询方式
     *
     * @param orderId 订单id
     * @return {@link Order}
     */
    @Override
    public Order getOrderById(Long orderId) {

        return jdbcTemplate.queryForObject("select * from t_order where id="+orderId, this::mapRowToOrder);
    }

    @Override
    public Order getOrderByIdOnCallback(Long orderId) {
        class OrderStatementCallback implements StatementCallback {

            @Override
            public Object handleResultSet(ResultSet rs) throws SQLException {
                List<Order> orders = new ArrayList<Order>();
                while (rs.next()) {
                    Order order = new Order(rs.getLong("id"), rs.getString("order_number"));
                    orders.add(order);
                }
                return orders;
            }
        }
        // 当然这里可以采用匿名内部类或lambda方式
        return (Order) callbackJdbcTemplate.executeQuery("select * from t_order where id=" + orderId, new OrderStatementCallback());
    }

    @Override
    public Order getOrderByIdOnTemplate(Long orderId) {
        return (Order)orderJdbcTemplate.executeQuery("select * from t_order where id=" + orderId);
    }

    /**
     * ResultSet的一行数据到Po的映射处理
     * 只需要给出一行的映射读取即可
     *
     * @param rs     rs
     * @param rowNum 行num
     * @return {@link Order}
     * @throws SQLException sqlexception异常
     */
    private Order mapRowToOrder(ResultSet rs, int rowNum) throws SQLException {
        return new Order(rs.getLong("id"), rs.getString("order_name"));
    }
}
